import {
  formatTime,
  arrayBufferToStr
} from '../../utils/util.js'
const app = getApp()


Page({
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    Custom: app.globalData.Custom,

    config: {
      serverIp: '192.168.130.243',
      serverPort: '9306',
      flash: 'auto',
      position: 'front',
      keepScreenOn: true,
      size: 'medium',
    },

    flashOption: [{
        name: '自动',
        value: 'auto'
      },
      {
        name: '开',
        value: 'on'
      },
      {
        name: '关',
        value: 'off'
      }
    ],

    positionOption: [{
        name: '前置',
        value: 'front'
      },
      {
        name: '后置',
        value: 'back'
      },
    ],

    sizeOption: [{
        name: '低',
        value: 'small'
      },
      {
        name: '中',
        value: 'medium'
      },
      {
        name: '大',
        value: 'large'
      }
    ],
    history: [],
    code: '',
    latestTime: '',

    pcConnection: false
  },


  /**
   * 读取配置
   */
  configInit() {
    let config = wx.getStorageSync('config');

    if (!config) {
      config = {
        serverIp: '192.168.1.1',
        serverPort: '9306',
        flash: 'auto',
        position: 'back',
        keepScreenOn: false,
        size: 'medium'
      }
    }

    let flashOption = this.data.flashOption
    let positionOption = this.data.positionOption
    let sizeOption = this.data.sizeOption

    for (let i in flashOption) {
      if (flashOption[i].value == config.flash) flashOption[i].checked = true
    }
    for (let i in positionOption) {
      if (positionOption[i].value == config.position) positionOption[i].checked = true
    }
    for (let i in sizeOption) {
      if (sizeOption[i].value == config.size) sizeOption[i].checked = true
    }

    wx.setKeepScreenOn({
      keepScreenOn: config.keepScreenOn,
    })

    this.setData({
      config: config,
      positionOption: positionOption,
      flashOption: flashOption,
      sizeOption: sizeOption
    })
  },



  onLoad() {

    this.configInit()

    this.udp = wx.createUDPSocket()
    this.port = this.udp.bind()

    this.udp.onMessage((res) => {
      let message = res.message
      let result = arrayBufferToStr(message)
      if (result ==='connectionSucceeded'){
        this.setData({ pcConnection:true})
      }else{
        this.playAudio()
        this.recordHistory(result)
      }
    })
  },

  /**
   * 测试连接
   */
  testConnection() {
    this.onLoad()
    let that = this
    this.setData({
      pcConnection: false,
      code: 'testConnection'
    })

    wx.showLoading({
      title: '正在测试连接...',
      mask: true
    })
    this.sendScanData()
    setTimeout(function() {
      if (that.data.pcConnection) {
        wx.hideLoading()

        wx.showModal({
          title: '提示',
          content: '当前连接正常!',
          showCancel:false
        })

      } else {
        wx.hideLoading()
        wx.showModal({
          title: '提示',
          content: '当前无连接!',
          showCancel: false
        })
      }
    }, 1000)

  },

  /**
   * 授权失败
   */
  error() {
    wx.showModal({
      showCancel: false,
      title: '提示',
      content: '使用扫描枪模式需要取得相机权限,请授权!',
      success(res) {
        if (res.confirm) {
          wx.openSetting({
            complete: function() {
              // 重定向
              wx.redirectTo({
                url: '/pages/scanningGunSimulation/scanningGunSimulation',
              });
            }
          })
        }
      }
    })

  },



  /**
   * 打开设置
   */
  showModal(e) {
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
  },
  /**
   * 隐藏设置
   */
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },


  /**
   * 历史扫描记录
   */
  recordHistory(code) {
    let history = this.data.history
    let existing = false

    for (let i in history) {
      if (history[i].code == code) {
        existing = true
        history[i].number = history[i].number + 1
        history[i].time = formatTime()
        break
      }
    }

    if (!existing) {
      history.push({
        code: code,
        number: 1,
        time: formatTime()
      })
    }

    this.setData({
      latestTime: formatTime(),
      history: history
    })
  },

  /**
   * 触发扫描
   */
  cameraScan(e) {
    let code = e.detail.result

    this.setData({
      code: code,
    })

    this.sendScanData()
  },


  scanClick(){
    let that = this
    wx.scanCode({
      onlyFromCamera: true,
      success (res) {
        that.setData({
          code: res.result,
        })
        that.sendScanData()
      },
  
    })
  },



  /**
   * 闪光灯变化
   */
  flashOptionChange(e) {
    let config = this.data.config
    config.flash = e.detail.value
    this.setData({
      config: config
    })
    this.setCache('config', config)
  },
  /**
   * 摄像头变化
   */
  positionOptionChange(e) {
    let config = this.data.config
    config.position = e.detail.value
    this.setData({
      config: config
    })
    this.setCache('config', config)
  },
  /**
   * 屏幕常亮变化
   */
  keepScreenOnChange(e) {
    let config = this.data.config
    config.keepScreenOn = e.detail.value
    wx.setKeepScreenOn({
      keepScreenOn: e.detail.value,
    })
    this.setData({
      config: config
    })
    this.setCache('config', config)
  },
  /**
   * 像素值变化
   */
  sizeOptionChange(e) {
    let config = this.data.config
    config.size = e.detail.value
    this.setData({
      config: config
    })
    this.setCache('config', config)
  },
  /**
   * ip端口输入变更
   */
  bindKeyInput(e) {
    let target = e.currentTarget.dataset.type
    let value = e.detail.value
    let config = this.data.config
    config[target] = value
    this.setData({
      config: config
    })

    this.setCache('config', config)
  },

  /**
   * 播放提示
   */
  playAudio() {
    let innerAudioContext = wx.createInnerAudioContext()
    innerAudioContext.autoplay = true
    innerAudioContext.src = '/static/audio/notification.wav'
  },


  /**
   * 配置缓存
   */
  setCache: function(key, value) {
    wx.setStorage({
      key: key,
      data: value,
    })
  },

  /**
   * 发送扫描内容
   */
  sendScanData() {
    let address = this.data.config.serverIp
    let port = this.data.config.serverPort
    let code = this.data.code
    this.udp.send({
      address: address,
      port: port,
      message: code
    })
  }

})